from django.db.models import Q
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model

User = get_user_model()

'''自定义用户验证类'''
class LoginBackend(BaseBackend):
    def authenticate(self, req, username=None, password=None):             # 当用户调用authenticate()方法时执行
        user = User.objects.get(Q(account=username) | Q(phone=username))   # 实现既可以根据username也可以根据phone等登陆
        if user and user.check_password(password):
            return user
        return None
    
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

